import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { Input } from 'antd-mobile';
import { AutoComplete } from 'antd';
import { connect, mapProps, useField } from '@formily/react';
import { Field } from '@formily/core';
import { getMessage } from '@inbiz/react';
import { useModelList } from '@inbiz/hooks';
import { useEvents } from '@inbiz/utils';
import { defaultProps } from '../../designer/schema';
import api from '../web/api';
import './index.less';

type IProps = {
  controlId: string;
  value: string;
  // onChange: Function
  readOnly: boolean;
  disabled: boolean;
  addonAfter: string;
  title: string;
  inbiz: { appInfo: { appId: string } };
  sourceModel: string;
  onChange: (value: string) => void;
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  viewMode?: string;
  emit?: {
    /** 自动完成框搜索内容变化时触发 */
    (type: 'onSerch', value?: any): void;
    /** 自动完成框选中条目时触发 */
    (type: 'onSelect', value?: string, options?: object): void;
  };
} & typeof defaultProps;

const iconNoEnterReg =
  /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;

const EformInput = forwardRef((props: IProps, ref: any) => {
  const [options, setOptions] = useState<{ value: string }[]>([]);
  const { addonAfter, autoComplete,autoCompleteFiled, placeholder,viewMode, ...others } = props;
  const formItemBoxProps: any = {};
  const [configEvents] = useEvents(props.callBackEvents, props.emit);
  const { runAsync, loading } = useModelList(configEvents);
  const filed = useField<Field>();

  useEffect(() => {
    if (
      autoCompleteFiled &&
      autoCompleteFiled?.length > 0 &&
      autoComplete == true &&
      (props.value || props.value?.length > 0)
    ) {
      runAsync({
        appId: props.inbiz.appInfo.appId,
        key: props.sourceModel,
        pageInfo: {
          index: 1,
          size: 10,
        },
        queryGroups: [
          {
            index: 0,
            connector: 'and' as const,
            query: [
              {
                connector: 'and' as const,
                operator: 'startwith' as const,
                field: autoCompleteFiled,
                value: props.value,
              },
            ],
          },
        ],
      }).then((data: any) => {
        let disposeData: any = [];
        const [modelName, fieldName] = autoCompleteFiled.split('$');
        if (data.Rows && data.Rows?.length > 0) {
          data.Rows.forEach((item: any) => {
            disposeData.push({ value: item[fieldName], key: item['id'] });
          });
        }
        setOptions(disposeData);
      });
    }
  }, [props.value]);

  useEffect(() => {
    if (!loading && (!props.value || props.value?.length < 0)) {
      setOptions([]);
    }
  }, [props.value, loading]);

  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents, props, filed),
    }),
    [options],
  );
  // 自动完成的专有方法
  const onSelect = (value: string, options: any) => {
    props.emit?.('onSelect', value, options);
  };
  const onSearch = (searchText: string) => {
    props.emit?.('onSerch', searchText);
  };

  let extras = [];
  // stylePage: object = { width };
  if (addonAfter) {
    extras.push(
      <span key="inlineUnit" className="extraItem">
        {addonAfter}
      </span>,
    );
  }
  if (extras.length) {
    formItemBoxProps.extra = extras;
  }
  return autoComplete ? (<>
    <AutoComplete
      {...others}
      style={{ lineHeight: '31px' }}
      // className="eformInput"
      disabled={props.readOnly || props.disabled}
      backfill
      options={options}
      onSelect={onSelect}
      onSearch={onSearch}
    >
      {viewMode == 'look' ? <div style={{fontSize:'16px'}}>{`${props.value?props.value:''}${props.addonAfter?props.addonAfter:''}`}</div>:
      <Input
        {...others}
        placeholder={placeholder}
        value={props.value || ''}
        style={{ margin: 0 }}
        onChange={(e) => {
          props?.onChange?.(e.target.value.replace(iconNoEnterReg, ''));
        }}
      />}
    </AutoComplete>
  </>
  ) : 
    <>
      {
        viewMode == 'look' ? <div style={{ fontSize: '16px' }}>{`${props.value ? props.value : ''}${props.addonAfter ? props.addonAfter : ''}`}</div> :
          <Input  {...others} value={props.value || ''} placeholder={placeholder} />
      }
    </>
});
EformInput.displayName = 'EformInput';
(EformInput as typeof EformInput & IDefaultValueFormat<typeof defaultProps>).defaultValueFormat = (
  props: any,
): string | void => {
  if (props.defaultValueType == 'custom') {
    return props.customValue;
  } else if (props.defaultValueType == 'system' && props.systemDefaultValue) {
    const { userInfoByToken } = props.inbiz.appInfo;
    const data = {
      System_Var_LoginUserID: userInfoByToken.ID,
      System_Var_LoginUserIdentityId: userInfoByToken.IdentityId,
      System_Var_LoginUserName: userInfoByToken.Name,
      System_Var_LoginUserDeptID: userInfoByToken.MainDepartmentId,
      System_Var_LoginUserDeptName: userInfoByToken.MainDepartmentName,
      System_Var_LoginUserPostID: userInfoByToken.MainPositionId,
      System_Var_LoginUserPostName: userInfoByToken.MainPositionName,
      System_Var_LoginUserAccount: userInfoByToken.Account,
    };
    let result = '';
    for (const key in data) {
      if (key == props.systemDefaultValue) {
        result = data[key];
      }
    }
    return result;
  }
  if (!props.value) {
    return '';
  }
};
export default connect(
  EformInput,
  mapProps({}, (props, field) => {
    const { allowClear, ...others } = props;
    if(props.viewMode!='look'){
      field.decoratorProps.addonAfter = props.addonAfter;
    }else{
      field.decoratorProps.addonAfter=''
    }
    others.clearable = allowClear;
    others.placeholder = getMessage(props.placeholder);
    return { ...others };
  }),
);
